from flask import Blueprint, render_template, redirect, url_for, flash, session, request, abort, current_app
from .posts import get_all_posts, save_post, delete_post, parse_post
import os
admin_bp = Blueprint('admin', __name__)


@admin_bp.route('/admin')
def admin():
    """后台管理首页"""
    if not session.get('logged_in'):
        return redirect(url_for('auth.admin_login'))
    return render_template('admin.html', posts=get_all_posts())


@admin_bp.route('/admin/post/new', methods=['GET', 'POST'])
def new_post():
    """新增博文"""
    if not session.get('logged_in'):
        return redirect(url_for('auth.admin_login'))

    if request.method == 'POST':
        title = request.form.get('title')
        content = request.form.get('content')
        slug = title.lower().replace(' ', '-')

        save_post(slug, title, content)
        flash('Post created successfully!', 'success')
        return redirect(url_for('admin.admin'))

    return render_template('edit.html', post=None)


@admin_bp.route('/admin/post/edit/<slug>', methods=['GET', 'POST'])
def edit_post(slug):
    """编辑博文"""
    if not session.get('logged_in'):
        return redirect(url_for('auth.admin_login'))

    post_path = os.path.join(current_app.root_path, 'posts', f'{slug}.md')
    post = parse_post(post_path)

    if not post:
        abort(404)

    if request.method == 'POST':
        title = request.form.get('title')
        content = request.form.get('content')

        save_post(slug, title, content)
        flash('Post updated successfully!', 'success')
        return redirect(url_for('admin.admin'))

    return render_template('edit.html', post=post)


@admin_bp.route('/admin/post/delete/<slug>')
def delete_post_route(slug):
    """删除博文"""
    if not session.get('logged_in'):
        return redirect(url_for('auth.admin_login'))

    delete_post(slug)
    flash('Post deleted successfully!', 'success')
    return redirect(url_for('admin.admin'))
